﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KagSharp.Expressions
{
    public class MacroExpression : TagExpression
    {
    	private string _MacroName;
    	public string MacroName { get{return _MacroName;}set{_MacroName = value;} }
        private List<IExpression> _Children;
        public List<IExpression> Children { get{return _Children;}set{_Children=value;} }

        public MacroExpression(
            string tagName, List<IExpression> parameters,
            List<IExpression> children)
            : base(tagName, parameters)
        {
            Children = children;
            MacroName = null;
            foreach (IExpression p in parameters)
            {
            	if (p.ValueType==typeof(ParameterExpression))
            	{
            		ParameterExpression p2 = (ParameterExpression)p;
            		if (p2.Name == "name")
            		{
            			MacroName = p2.Value.ToString();
            			break;
            		}
            	}
            }
            /*
            MacroName = parameters
                .Where(p => p.ValueType==typeof(ParameterExpression))
                .Cast<ParameterExpression>()
                .FirstOrDefault(p => p.Name == "name")?
                .Value.ToString();*/
        }

        public override void Print(StringBuilder sb, bool verbose, int indentLevel)
        {
            ExpressionHelper.Indent(sb, GetType(), indentLevel);
            sb.Append("[macro");
            if (Parameters != null && Parameters.Count > 0)
            {
                sb.Append(' ');
                ExpressionHelper.PrintDelimited(sb, Parameters, " ", verbose);
            }
            sb.Append("]");
            ExpressionHelper.PrintDelimited(sb, Children, "", verbose, ++indentLevel);
            ExpressionHelper.Indent(sb, GetType(), --indentLevel);
            sb.Append("[endmacro]");
        }

        public override TR Accept<TR>(IExpressionVisitor<TR> visitor, string context) {
        	return visitor.Visit(this, context);}

        public override Type ValueType {get{return typeof (TagExpression);}}

        public override string ToString() {return "MacroExpression: " + MacroName;}
    }
}
